package com.yuebao.utils;

import com.yuebao.exception.CustomerException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.RedissonMultiLock;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Component
@Slf4j
@RequiredArgsConstructor
public class RedissonService {
    
   
    
    public static final String FUND_STOCK = "lock:stock";
    
    
   
    
    
    private final RedissonClient redissonClient;
    
    
    public boolean tryRedLock(String prefix,String lockKey) throws CustomerException {
        
        String key = prefix + lockKey;
        try{
        // 要在bean注册链接多个redisson客户端 redissonClient。。。123 这里单机代替
        RLock lock1 = redissonClient.getLock(key);
        RLock lock2 = redissonClient.getLock(key);
        RLock lock3 = redissonClient.getLock(key);
    
        RedissonRedLock redLock=new RedissonRedLock(lock1,lock2,lock3);
        
            
            boolean isSuccess = redLock.tryLock(5,180,TimeUnit.SECONDS);
            if(!isSuccess){
                return false;
            }
            return true;
        } catch (InterruptedException e) {
            throw new CustomerException("分布式锁错误："+e.getMessage());
        }
        
    }
    public boolean unlockRedLock(String prefix,String lockKey){
        //无论是否加没加 要把所有客户端都解锁
        String key = prefix + lockKey;
        // 要在bean注册链接多个redisson客户端 redissonClient。。。123 这里单机代替
        try{
            RLock lock1 = redissonClient.getLock(key);
            RLock lock2 = redissonClient.getLock(key);
            RLock lock3 = redissonClient.getLock(key);
    
            RedissonRedLock redLock=new RedissonRedLock(lock1,lock2,lock3);
    
            redLock.unlock();
            return true;
        }catch (Exception e){
            log.error("解锁失败{}",key,e);
            return false;
        }
        
    }
   
}
